<template>
  <section class="ueditor-content" v-loading="loading">
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible" width="30%" custom-class="reset-pwd wlm-form-dialog dialog-table">
      <div class="wlm-form" v-if="dialogVisible">
        <div class="wlm-form-header wlm-dialog-fixheader">
          <span class="wlm-dialog-inlenr">微信图文采集</span>
        </div>
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <div class="wlm-form-content">
            <div class="wlm-dialog-main">
              <div class="wlm-dialog-content flex-col">
                <p>1.下方表单输入链接，可以采集微信内容链接。例如：https://mp.weixin.qq.com/s/MQs5zQcYQlI_RCkf91BgXg</p>
                <p style="margin-top:10px;">2.可以使用微信内容复制到编辑器中即可。由于图片采集需要时间。所以等待20秒再提交表单。</p>
                <p style="margin-top:10px;">温馨提示：视频，过于复杂的样式，背景图，可能会导致采集失败。</p>
                <el-input style="margin-top:10px;width:90%;" placeholder="采集微信图文内容（填写微信图文链接）" v-model="materialNewsText">
                </el-input>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <footer class="flex-row flex-align-c flex-justify-c wlm-dialog-fixfooter">
        <el-button size="text" type="primary" @click="dialogVisible=false">取消</el-button>
        <el-button size="small" type="primary" :disabled="dialogLoding" :loading="dialogLoding" @click="saveTextarea">采集</el-button>
      </footer>
    </el-dialog>
    <choose-files ref="chooseFiles" :config="chooseFilesConfig" :changeEvt="uploadFileChange"></choose-files>
    <choose-files ref="chooseVideoFiles" :config="chooseFilesVideoConfig" :changeEvt="uploadFileChange"></choose-files>
    <el-button class="imoprt-uedotor" type="primary" size="mini" @click="dialogVisible = true">一键导入图文</el-button>
    <vue-ueditor-wrap v-if="!destoryed" v-show="!destoryed" v-model="msg" @ready="ready" :destroy="true" :config="ueditorConfig" :init="ueditorInit" ref="ueditor"></vue-ueditor-wrap>
    <p class="orders-gray font-12" style="margin-top:10px;">建议使用图片作为详情内容，从其他编辑器或者平台粘贴可能会出现样式问题，请手动修改。</p>
    <p class="orders-gray font-12">样式有问题的建议先粘贴到word文档（无格式粘贴）再复制到后台</p>
  </section>
</template>

<script>
import { mapGetters } from 'vuex'
import VueUeditorWrap from 'vue-ueditor-wrap'
import ChooseFiles from '@/components/ChooseFiles/index'
import {
  getWechatNews
} from '@/api/user'
export default {
  name: 'UE',
  data() {
    return {
      materialNewsText: '',
      dialogVisible: false,
      dialogLoding: false,
      destoryed: false,
      loading: true,
      msg: '',
      isReady: false,
      chooseFilesConfig: {
        type: ['image'],
        model: 'normal',
        initList: [],
        file_type: 'image'
      },
      chooseFilesVideoConfig: {
        type: ['video'],
        model: 'normal',
        initList: [],
        file_type: 'video'
      },
      ueditorConfig: {
        UEDITOR_HOME_URL: './static/UEditor/',
        autoHeightEnabled: false,
        maximumWords: 20000,
        initialFrameHeight: 340,
        initialFrameWidth: '100%',
        enableAutoSave: false,
        toolbars: [
          [
            'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'horizontal', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', 'indent', '|',
            'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', 'fullscreen', '|',
            'paragraph', 'fontsize', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
            'link','|',
            '135editor'
          ]
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'permission_routers',
      'sidebar'
    ])
    // isHiddenUeditor() {
    //   return this.sidebar.hideUeditor
    // }
    // isMore() {
    //   return this.bindIndex && this.ueditorList && Array.isArray(this.ueditorList) && this.ueditorList.length > 0
    // }
  },
  components: {
    ChooseFiles,
    VueUeditorWrap
  },
  watch: {
    //  <!-- JSON.parse(JSON.stringify(chooseFilesConfig)) -->

    'defaultMsg': {
      handler(newData, oldData) {
        if (typeof newData === 'string' && newData !== '') {
          this.msg = newData
        }
      },
      immediate: true,
      deep: true
    }
  },
  props: {
    defaultMsg: {
      type: String
    },
    bindIndex: {
      type: Number,
      required: false
    },
    ueditorList: {
      type: Array,
      required: false
    },
    config: {
      type: Object
    },
    ueditorChange: {
      type: Function
    },
    defaultFocus: {
      type: Boolean
    },
    ueditorDisabled: {
      type: Boolean,
      default: false
    }
  },
  mounted() {

  },
  methods: {
    saveTextarea() {
      const Base64 = require('js-base64').Base64
      this.dialogLoding = true
      getWechatNews({ url: this.materialNewsText }).then((response) => {
        const {
          data: {
            data: msgData = []
          }
        } = response
        const contentBase = Base64.decode(msgData)
        this.msg = contentBase
        this.materialNewsText = ''
        this.dialogVisible = false
        this.dialogLoding = false
      })
    },
    uploadFileChange(file) {
      const { displayData: fileList } = file
      this.$Ueditor.focus()
      if (fileList.length > 0) {
        fileList.map((item) => {
          if (item.file_type !== 'video') {
            this.$Ueditor.execCommand('inserthtml', `<img style="font-size: 0px;line-height: 0px;vertical-align: middle;max-width: 100%;" src="${item['file_path']}"/>`)
          } else {
            this.$Ueditor.execCommand('inserthtml', `<video class="video-ueditor" src="${item['file_path']}" controls="controls"/>`)
            // this.$Ueditor.execCommand('insertvideo', {
            //   url: item['file_path'],
            //   width: 300,
            //   height: 200
            // })
          }
        })
      }
    },

    // uploadSaveChange(fileList) {
    //   // if (this.isMore) {
    //   //   this.$Ueditor = this.ueditorList[this.bindIndex]
    //   // }
    //   this.$Ueditor.focus()
    //   if (fileList.length > 0) {
    //     fileList.map((item) => {
    //       if (item.file_type !== 'video') {
    //         this.$Ueditor.execCommand('inserthtml', `<img style="font-size: 0px;line-height: 0px;vertical-align: middle;max-width: 100%;" src="${item['file_path']}"/>`)
    //       } else {
    //         this.$Ueditor.execCommand('insertvideo', {
    //           url: item['file_path'],
    //           width: 300,
    //           height: 200
    //         })
    //       }
    //     })
    //     // console.log(this.defaultFocus)
    //   }
    //   // console.log(this.$Ueditor.execCommand);
    // },
    ueditorInit(...arg) {
      const UE = window.UE
      const that = this
      // 自定义上传图片和视频按钮
      UE.registerUI('buttonimg', function(editor, uiName) {
        // 创建一个button
        var btn = new UE.ui.Button({
          // 按钮的名字
          name: '上传图片',
          // 提示
          title: '上传图片',
          // 添加额外样式，指定icon图标，这里默认使用一个重复的icon
          cssRules: 'background-position: -726px -77px;',
          // 点击时执行的命令
          onclick: function() {
            // 这里可以不用执行命令,做你自己的操作也可
            // editor.execCommand(uiName);
            // 执行自定义上传
            // JSON.parse(JSON.stringify())
            that.$Ueditor.focus()
            // console.log(that.$Ueditor, that.ueditorList)
            // that.$refs.upload.uploadTrigger()
             setTimeout(() => {
                   that.$refs.chooseFiles.toggle()
                      // console.log(this.$refs.msgText) // <p data-v-5752faac="" style="color: rgb(238, 238, 238);">msg show</p>
                    }, 10)
          }
        })
        // 当点到编辑内容上时，按钮要做的状态反射
        editor.addListener('selectionchange', function() {
          var state = editor.queryCommandState(uiName)
          if (state === -1) {
            btn.setDisabled(true)
            btn.setChecked(false)
          } else {
            btn.setDisabled(false)
            btn.setChecked(state)
          }
        })
        // 返回button
        return btn
      })
     //自定义135编辑器按钮
       UE.registerUI('135editor',function(editor,uiName){
    var editor135;
    function onContentFrom135(event) {
        if (typeof event.data !== 'string') {
            if(event.data.ready) {
                editor135.postMessage(editor.getContent(),'*');
            }
            return;
        };

        if(event.data.indexOf('<') !== 0) return;

        editor.setContent(event.data);
        editor.fireEvent("catchRemoteImage");
        window.removeEventListener('message', onContentFrom135);
    }

    var btn = new UE.ui.Button({
        name:'btn-dialog-' + uiName,       
        className:'edui-for-135editor',
        title:'135编辑器',
        onclick:function () {
            // dialog.render();
            // dialog.open();

            editor135 = window.open('https://www.135editor.com/simple_editor.html?callback=true&appkey=')
            
            window.removeEventListener('message', onContentFrom135);
            window.addEventListener('message', onContentFrom135, false);
        }
    });
    return btn;
})


    },
    ready(editorInstance) {
      this.loading = false
      this.$Ueditor = editorInstance
      this.$UeditorKey = editorInstance.key
      if (this.ueditorDisabled) {
        this.$Ueditor.setDisabled()
      }
      // this.ueditorList.push(editorInstance)
      // console.log(editorInstance, 'editorInstance')
      if (Object.prototype.toString.call(this.ueditorChange) === '[object Function]') {
        this.$Ueditor.addListener('contentChange', (res) => {
          const content = this.getUEContent('getContent')
          // this.$Ueditor.focus()
          this.ueditorChange(content, this.isReady)
          this.isReady = true
          // console.log(content, 'contentChange')
        })
        this.$Ueditor.addListener('afterSelectionChange', () => {
          const content = this.getUEContent('getContent')
          // this.$Ueditor.focus()
          this.ueditorChange(content)
        })
      }
    },
    setDisabled() {
      if (this.$Ueditor) {
        this.$Ueditor.setDisabled()
      }
    },
    getUEContent(getType = 'getPlainTxt') {
      // 获取内容方法
      return this.$Ueditor[getType]()
    }
  },
  beforeDestroy() {
    this.destoryed = true
  },
  destoryed() {
    this.$Ueditor.destory()
  }
}
</script>

<style lang="scss" scoped>
.edui-button.edui-for-135editor .edui-button-wrap .edui-button-body .edui-icon{

    background-image: url("http://static.135editor.com/img/icons/editor-135-icon.png") !important;

    background-size: 85%;

    background-position: center;

    background-repeat: no-repeat;

}
.ueditor-content {
  width: 785px;
  position: relative;
  z-index: 0;
}

.imoprt-uedotor {
  position: absolute;
  padding: 5px;
  font-size: 12px;
  top: 34px;
  right: 4px;
  z-index: 99999;
}

/deep/ .edui-editor div {
  line-height: 20px;
  padding-bottom: 2px;
}

/deep/ .edui-default .edui-editor-toolbarboxouter {
  border-bottom: none !important;
  background-image: none !important;
}

/deep/ .edui-default .edui-editor-breadcrumb {
  margin: 5px 0 0 6px !important;
}

/deep/ .edui-default .edui-editor-toolbarbox {
  border-bottom: 0;
  box-shadow: none;
  background-color: #fafafa;
  z-index: 99999;
}

// .edui-default iframe img{
//     font-size: 0px;
//     line-height: 0px;
//     vertical-align: middle;
//     max-width: 100%;
// }
/deep/ .edui-default iframe body {
  overflow-x: hidden;
}

/deep/ textarea[name="editorValue"] {
  display: none !important;
}
</style>
